package org.restorator.controller.security;


import org.restorator.entity.User;
import org.restorator.service.UserService;
import org.restorator.service.impl.UserServiceImpl;
import org.restorator.utill.ControllerUtil;
import org.restorator.utill.GeneralUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;

/**
 * @author Snisar Bogdan.
 */
@WebFilter(filterName = "secure", urlPatterns = "/**")
public class SecurityFilter implements Filter {

    private static Logger logger = LoggerFactory.getLogger(GeneralUtil.getClassName());
    private static final String LOGIN = "/login";
    private static final String USER = "/user";

    /**
     * Parameter that must be in all requests (escape allowed urls) for security permission.
     */
    private static final String ATTR_KEY = "key";

    /**
     * Service for using user key checking
     */
    private UserService userService;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        userService = new UserServiceImpl();
        logger.trace("init secur filter!");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        String url = req.getServletPath();
        logger.debug("Request URL: {}", url);

        try {
            if(LOGIN.equals(url) || USER.equals(url)) { //used for to allowed url requests with no key checking
                logger.trace("allowed url");
                chain.doFilter(request, response);
                return;
            }

            String userKey = req.getParameter(ATTR_KEY);
            if(userKey != null && !userKey.isEmpty()) {
                logger.trace("parameter find {}", userKey);
                User user = userService.getUserByKey(userKey);
                if(user != null) {
//                    Ok
                    chain.doFilter(request, response);
                    return;
                }
            }
            ControllerUtil.printError(resp, "not enough permission");
        } catch (Exception e) {
            logger.trace("Except {}", e);
//            ControllerUtil.printError(resp.getWriter(), "erroe");
            resp.sendError(HttpServletResponse.SC_BAD_GATEWAY); //wtf?

        }


    }

    @Override
    public void destroy() {
        userService = null;
    }
}
